"""
Demo for loading files from our NN Learning Curve repo https://doi.org/10.7910/DVN/ZXTCGF and calculating and saving metrics of interest.

BSD 3-Clause License

Copyright (c) 2021, Global Computing Lab
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import pandas as pd
import numpy as np
import os
#import shutil

# save all the models you wish to investigate into a single directory, with no other .txt files in it, and update DATAFILES_DIRECTORY to match
DATAFILES_DIRECTORY = "CIFAR-100_models"

# make a list of all non-hidden data files in the directory with .txt extension--these will be all the NN models to investigate
datafiles=[]
for item in os.scandir(DATAFILES_DIRECTORY):
    if item.name.endswith(".txt") and not item.name.startswith("."):
        datafiles.append(item.path)

# if you wish to calculate some information for each one of the NNs and save aggregate info, create empty lists for the info you wish to save
# for example, if I want a list of the learning rate of each NN, mean accuracy of each NN, min acc of each NN, and a list of the associated NN IDs:
learningRateList = []
meanAccList = []
minAccList = []
nnIDList = []

# if you wish to save calculated information, enter the path to save it to here
SAVEFILE = "saved_calculations.csv"

# looping through each NN file
for FILENAME in datafiles:

    # load a dataframe containing the learning curve and structure info for the NN stored at FILENAME
    data = pd.read_csv(FILENAME, sep=" ", header="infer")

    # sort the data by epochs to ensure it is correctly ordered
    sortedData=data.sort_values(by="epochs", axis=0, ascending=True)

    # grab data of interest by isolating particular columns by name
    # e.g. the validation accuracy learning curve is given by the "valAcc" column of the dataframe.
    validationAccCurve=np.array(sortedData["valAcc"])
    validationLossCurve=np.array(sortedData["valLoss"])

    # parameters of the NN that do not change throughout training are recorded just in the first row
    # for example, layer types, the kernels used for all convolutional layers, or the learning rate.
    # grab this info by specifying the corresponding column and the first row (row 0)
    learningRate=np.array(sortedData["learning_rate"])[0]
    convolutionKernels=np.array(sortedData["convKernels"])[0]

    # get the ID of the NN stored at FILENAME by specifying column "ID" and row 0
    nnID = np.array(sortedData["ID"])[0]

    # perform desired calculations with the data; e.g. calculate the max, min, and mean validation accuracy
    maxAcc = validationAccCurve.max()
    minAcc = validationAccCurve.min()
    meanAcc = validationAccCurve.mean()

    # append info to save to the associated lists
    learningRateList.append(learningRate)
    minAccList.append(minAcc)
    meanAccList.append(meanAcc)
    nnIDList.append(nnID)

    # print any info, e.g. mean accuracy of the given NN to 4 decimal places
    print("Mean validation accuracy of NN " + str(nnID) + " is {:.4f}".format(meanAcc))

# save calculated info:
# begin by creating a dictionary that associates the desired column names with the calculated info to save
dataDict = {"nnID":nnIDList, "NNlearningRate":learningRateList, "meanNNacc":meanAccList, "minNNacc":minAccList}

# create a dataframe from the dictionary
dataDF = pd.DataFrame(dataDict)

# save the dataframe as a csv at path SAVEFILE. Note that sep specifies the separator; with sep=" ", columns are separated by spaces.
dataDF.to_csv(SAVEFILE, sep=" ", index=False, header=True)